import {Injectable, OnModuleInit} from '@nestjs/common';
import * as net from "node:net";
import {breathConfig} from "../../../config";

@Injectable()
export class MockGatewaySignalServerService implements OnModuleInit {
    server: net.Server;

    onModuleInit() {
        if (!breathConfig.openMockGateSignalFlag) {
            return;
        }
        console.log("Mock Gateway Signal Server init");
        this.start();
    }

    start() {
        let flag = true
        const server = net.createServer((socket) => {
            console.log("Client connected");

            const sendSignal = () => {
                if (socket.destroyed) {
                    return;
                }
                const buffer = new ArrayBuffer(1);
                const view = new Uint8Array(buffer);
                if (flag) {
                    view[0] = 1;
                } else {
                    view[0] = 0;
                }
                flag = !flag
                try {
                    socket.write(view)
                }catch (e) {
                    console.log(`mock gate signal message send failed: ${e.message}`);
                }
                setTimeout(sendSignal, 3000);
            }


            sendSignal()

            // 处理关闭事件
            socket.on("end", () => {
                console.log("Client disconnected");
            });

            // 处理错误事件
            socket.on("error", (err) => {
                console.error("Socket error:", err);
            });
        });

        // 服务器监听在指定端口
        const PORT = breathConfig.mockGatewaySignalPort;
        server.listen(PORT, () => {
            console.log(`Mock Gateway Signal Server TCP server is running on port ${PORT}`);
        });
    }

}
